import router from '@/router'
import { useLoginUserStore } from '@/stores/user.ts'
import { ACCESS_ENUM, checkAccess } from '@/router/role.ts'

/**
 * 全局权限校验
 */
router.beforeEach(async (to, from, next) => {
  const loginUserState = useLoginUserStore();
  let loginUser = loginUserState.loginUser;
  const needAccess = (to.meta?.authCheck as string) ?? ACCESS_ENUM.NOT_LOGIN
  // 之前没登录过，自动登录
  if (!loginUser || !loginUser.userRole) {
    await loginUserState.fetchLoginUser();
    loginUser = loginUserState.loginUser;
  }
  // 要跳转的页面必须登录
  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    // 没登录 跳转登录页面
    if (!loginUser || !loginUser.userRole || loginUser.userRole === ACCESS_ENUM.NOT_LOGIN) {
      next(`/user/login?redirect=${to.fullPath}`)
      return
    }
    // 已登录，如果权限不足则进入无权限页面
    if (!checkAccess(loginUser, needAccess)) {
      next('/noAuth')
      return
    }
  }
  next()
})
